import { expect } from '@jest/globals';
import * as compressing from 'compressing';
import fsExtra from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { initExecuteCommand, runHvigor } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    [ModuleTemplateType.SharedLibrary]: 1,
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};

const testFun: (module?: string) => TestCaseFun = (module?: string) => async (project, taskConfig, record) => {
  const libraryModulePath = project.getModule('shareLibrary').moduleRootPath();

  // 读取的 路径 path.resolve(project.getModule('library').moduleRootPath(),'build-profile.json5');
  const bufferFeature =
    await fsExtra.readFile(path.resolve(libraryModulePath, 'build-profile.json5'));
  const featureBuildProfileJson = JSON5.parse(bufferFeature.toString());

  const libraryEnable = featureBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.ruleOptions.enable;

  // 在library模块中的混淆文件中配置代码混淆规则
  const str = '\n-enable-toplevel-obfuscation\n-compact';
  await fsExtra.appendFile(path.resolve(libraryModulePath, 'obfuscation-rules.txt'), str);

  // buildMode为none时，选择build APP
  const projectRoot = project.projectRootPath();
  const commands = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp',

    // , ...(module ? { module: `${module}@default` } : {})
  });
  const result = runHvigor(projectRoot, commands);

  // library中得到混淆后的hap产物，查看备注中的js文件

  const libraryBuffer = await fsExtra.readFile(path.resolve(libraryModulePath,
    'build/default/cache/default/default@CompileArkTS/esmodule/release/shareLibrary/src/main/ets/pages/Index.ts'));
  const stringLibrary = libraryBuffer.toString().split('\n');
  const libraryObfuscation: boolean = stringLibrary.length > 2;

  // library模块hsp包的根路径下不含有文件obfuscation.txt
  await fsExtra.copyFile(path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned.hsp'),
    path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned.zip'));
  // eslint-disable-next-line max-len
  await compressing.zip.uncompress(path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned.zip'),
    path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned'));
  const libraryObfuscationExist =
    // eslint-disable-next-line max-len
    await fsExtra.pathExists(path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned/obfuscation-rules.txt'));

  const commandsClean = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'clean'
    , ...(module ? { module: `${module}@default` } : {})
  });
  runHvigor(projectRoot, commandsClean);

  const commandsSecond = initExecuteCommand({
    mode: 'module',
    buildMode: 'release',
    product: 'default',
    tasks: 'assembleHap'
    , ...(module ? { module: `${module}@default` } : {})
  });
  const resultSecond = runHvigor(projectRoot, commandsSecond);

  // library中得到混淆后的hsp产物，查看备注中的js文件

  const libraryBufferSecond = await fsExtra.readFile(path.resolve(libraryModulePath,
    'build/default/cache/default/default@CompileArkTS/esmodule/release/shareLibrary/src/main/ets/pages/Index.ts'));
  const libraryEntrySecond = libraryBufferSecond.toString().split('\n');
  const libraryObfuscationSecond: boolean = libraryEntrySecond.length > 2;


  // feature模块hap包的根路径下不含有文件obfuscation.txt
  // eslint-disable-next-line max-len
  await fsExtra.copyFile(path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned.hsp'),
    path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned.zip'));
  // eslint-disable-next-line max-len
  await compressing.zip.uncompress(path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned.zip'),
    path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned'));
  const libraryObfuscationExistSecond =
    // eslint-disable-next-line max-len
    await fsExtra.pathExists(path.resolve(libraryModulePath, 'build/default/outputs/default/shareLibrary-default-unsigned/obfuscation-rules.txt'));

  record.addStep('执行App编译构建', result);
  record.addStep('执行Hap编译构建', resultSecond);
  expect(libraryEnable).toBe(true);
  expect(libraryObfuscation).toBe(false);
  expect(libraryObfuscationExist).toBe(false);
  expect(libraryObfuscationSecond).toBe(false);
  expect(libraryObfuscationExistSecond).toBe(false);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  expect(resultSecond.stdout).toContain('BUILD SUCCESSFUL');


};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_ZOS_HOS_Build_App_Stage_ArkTS_obfuscation_006')
  .description('混淆默认开启时打hsp包')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun('entry'))
  .load();
